<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Cat;
class CatController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cat = $this->findAll();
        // dd($cat);
        return view('admin/cat_index')->with('cat',$cat);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cat = $this->findAll();
        return view('/admin/cat_add')->with('cat',$cat);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {   
        // dd($request);
        $cat = new Cat();
        $cat->parentid=$request->parentid;
        $cat->catname=$request->catname;
        // dd($cat);
        $cat->save();
        return redirect('/admin/cat');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    //格式化取出栏目
    protected function findAll()
    {
        $data = Cat::select('catid','parentid','catname')->get();
        return $this->findTree($data,0,0);
    }

    /**
     * 找子栏目
     */

    protected function findTree($data,$id=0,$lev=0)
    {
        static $tree=[];
        foreach($data as $v){
            if($v->parentid == $id){
                $v->lev=$lev;
                $tree[]=$v;
                $this->findTree($data,$v->catid,$lev+1);
            }
        }
        return $tree;
    }

}
